//
//  AddCategoryViewController.m
//  iRSSNews
//
//  Created by bk_sport on 12/28/12.
//  Copyright (c) 2012 bk_sport. All rights reserved.
//

#import "AddCategoryViewController.h"
#import "AppDelegate.h"
#import "Category.h"
#import "CategoriesViewController.h"

@interface AddCategoryViewController ()
{
    int rowEditName;
    Category *cate;
}

@end

@implementation AddCategoryViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    NSError *error;
	if (![[self fetchedResultsController] performFetch:&error]) {
		NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
		exit(-1);
	}
    
    cate = [self.fetchedResultsController.fetchedObjects objectAtIndex:self.selectedRow];
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(buttonDoneClick:)];
    
    if (_isAdd == YES)
    {
        self.title = NSLocalizedString(@"AddCategoryKey", @"");
        self.nameLB.text = NSLocalizedString(@"CategoryNameKey", @"");
    }
    else
    {
        self.title = NSLocalizedString(@"EditCategoryKey", @"");
        self.nameLB.text = NSLocalizedString(@"NewCategoryNameKey", @"");
        self.nameTF.text = cate.name;
    }
    self.nameTF.delegate = self;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}

- (void) buttonDoneClick:(id) sender
{
    AppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
    NSManagedObjectContext *context = appDelegate.managedObjectContext;
    
    NSString *string = self.nameTF.text;
    NSString *trimedString = [string stringByTrimmingCharactersInSet:
                              [NSCharacterSet whitespaceCharacterSet]];
    if (_isAdd == YES)
    {
        if(trimedString.length != 0)
        {
            NSUserDefaults *standardUserDefaults = [NSUserDefaults standardUserDefaults];
            NSInteger numberOfCategories = [standardUserDefaults integerForKey:@"numberOfCategories"];

            Category *item = [NSEntityDescription
                              insertNewObjectForEntityForName:@"Category"
                              inManagedObjectContext:context];
            item.id = [NSNumber numberWithInt:numberOfCategories];
            NSLog(@"%i", numberOfCategories);
            item.name = self.nameTF.text;
            
            //Du lieu gia cho numberOfNews
            item.numberOfNewNews=[NSNumber numberWithInt:30];

            NSError *error;
            if (![context save:&error]) {
                NSLog(@"Whoops, couldn't save: %@", [error localizedDescription]);
            }
            
            numberOfCategories++;
            [standardUserDefaults setInteger:numberOfCategories forKey:@"numberOfCategories"];
            [standardUserDefaults synchronize];
            
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"iRSSNews" message:NSLocalizedString(@"AlertAddCategoryOKKey", @"") delegate:sender cancelButtonTitle:NSLocalizedString(@"OKKey", @"") otherButtonTitles:nil];
            [alert show];
            [self.navigationController popToRootViewControllerAnimated:YES];
        }
        else
        {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"iRSSNews" message:NSLocalizedString(@"AlertAddCategoryFailedKey", @"") delegate:sender cancelButtonTitle:NSLocalizedString(@"OKKey", @"") otherButtonTitles:nil];
            [alert show];
            [self.nameTF becomeFirstResponder];
        }
    }
    else
    {
        if(trimedString.length != 0)
        {
            
            cate.name = self.nameTF.text;
            
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"iRSSNews" message:NSLocalizedString(@"AlertEditCategoryOKKey", @"") delegate:sender cancelButtonTitle:NSLocalizedString(@"OKKey", @"") otherButtonTitles:nil];
            [alert show];
            
            NSError *error;
            if (![context save:&error]) {
                NSLog(@"Whoops, couldn't save: %@", [error localizedDescription]);
            }
            
            [self.navigationController popToRootViewControllerAnimated:YES];
        }
        else
        {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"iRSSNews" message:NSLocalizedString(@"AlertEditCategoryFailedKey", @"") delegate:sender cancelButtonTitle:NSLocalizedString(@"OKKey", @"") otherButtonTitles:nil];
            [alert show];
            [self.nameTF becomeFirstResponder];
        }

    }
    
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [self.nameTF resignFirstResponder];
    return YES;
}

#pragma mark - fetchedResultsController

- (NSFetchedResultsController *)fetchedResultsController
{
    AppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
    
    if (_fetchedResultsController != nil) {
        return _fetchedResultsController;
    }
    static NSString *EntityName = @"Category";
    static NSString *CacheName = @"Category";
    [NSFetchedResultsController deleteCacheWithName:@"Category"];
    
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc]init];
    NSEntityDescription *entity = [NSEntityDescription entityForName:EntityName inManagedObjectContext:appDelegate.managedObjectContext];
    NSSortDescriptor *sort = [NSSortDescriptor sortDescriptorWithKey:@"id" ascending:YES];
    fetchRequest.entity = entity;
    fetchRequest.sortDescriptors = @[sort];
    fetchRequest.fetchBatchSize = 20;
    
    _fetchedResultsController = [[NSFetchedResultsController alloc]initWithFetchRequest:fetchRequest managedObjectContext:appDelegate.managedObjectContext sectionNameKeyPath:nil cacheName:CacheName];
    _fetchedResultsController.delegate = self;
    
    return _fetchedResultsController;
}


@end
